class Hero {
  constructor(config) {
    this.width = config.width;
    this.height = config.height;
    this.x = (480 - config.width) / 2;
    this.y = 700 - config.height;
    this.frame = config.frame;
    this.frameLiveIndex = 0;
    this.frameDeathIndex = 0;
    this.lastTime = new Date().getTime()
    this.speed = config.speed
    // 当前展示的图片
    this.img = null;
    this.live = true;
    // 子弹上次射击的时间
    this.lastShootTime = new Date().getTime();
    // 子弹射击的频率
    this.shootInterval = 150;
    // 弹夹
    this.bulletList = [];
    this.destroy = false;
  }
  judge() {
    const currentTime = new Date().getTime();
    if (currentTime - this.lastTime > this.speed) {
      if (this.live) {
        this.img = this.frame.live[this.frameLiveIndex++ % this.frame.live.length]
      } else {
        this.img = this.frame.death[this.frameDeathIndex++];
        if (this.frameDeathIndex === this.frame.death.length) {
          this.destroy = true;
        }
      }
      this.lastTime = currentTime
    }
  }
  paint(context) {
    // this.img = this.frame.live[0]
    context.drawImage(this.img, this.x, this.y)
  }
  // 战机射击子弹
  shoot() {
    // 获取当前时间
    const currentTime = new Date().getTime();
    if (currentTime - this.lastShootTime > this.shootInterval) {
      // 飞机头部初始化一个子弹对象
      let bullet = new Bullet(BULLET, this.x + this.width / 2 - BULLET.width / 2, this.y - BULLET.height);
      // 飞机认领这个子弹
      this.bulletList.push(bullet)
      // 在网页绘制一个子弹对象
      bullet.paint(context)
      // 更新飞机射击时间
      this.lastShootTime = currentTime
    }
  }
  // 与敌机碰撞
  collide() {
    // 碰到即死
    this.live = false;
  }
}
